// components/GoodItem/index.js
import { addCollectApi, cancelCollectApi } from '../../api/goods'
Component({
  options: {
    styleIsolation: 'shared'
  },
  observers: {
    detail: function (detail) {
      this.setData({
        goodsInfo: detail
      })
    }
  },
  /**
   * 组件的属性列表
   */
  properties: {
    isLogin: {
      type: Boolean,
      value: false
    },
    isOrder: {
      type: Boolean,
      value: false
    },
    detail: {
      type: Object,
      value: {}
    },
    isLink: {
      type: Boolean,
      value: true
    },
    border: {
      type: Boolean,
      value: true
    },
    showCollect: {
      type: Boolean,
      value: true
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    isLogin: false,
    goodsInfo: null
  },

  /**
   * 组件的方法列表
   */
  methods: {
    jumpGoodInfo() {
      if (!this.data.isLink) return
      wx.navigateTo({
        url: `/pages/goodinfo/goodinfo?goodId=${this.data.detail.id}`
      })
    },

    /**
     * 点击收藏按钮回调
     */
    collectHandle() {
      wx.showToast({
        title: '收藏按钮',
        icon: 'none'
      })
      !this.data.goodsInfo.collected ? this.addCollect() : this.cancelCollect()
      this.triggerEvent('collectBtnClick')
    },

    /**
     * 收藏
     */
    async addCollect() {
      const [err] = await addCollectApi({ productId: this.data.detail.id })
      if (err) return
      wx.showToast({
        title: '已收藏',
        icon: 'none'
      })
      this.setData({
        'goodsInfo.collected': true
      })
    },

    /**
     * 取消收藏
     */
    async cancelCollect() {
      const [err] = await cancelCollectApi({ productId: this.data.detail.id })
      if (err) return
      wx.showToast({
        title: '已取消收藏',
        icon: 'none'
      })
      this.setData({
        'goodsInfo.collected': false
      })
    },
    loginSuccess() {
      this.triggerEvent('loginSuccess')
    }
  },
  lifetimes: {
    attached() {
      this.setData({
        goodsInfo: this.data.detail
      })
    }
  }
})
